# -*- coding: utf-8 -*-

#this will translate a web page to another language

from urllib import urlopen
from BeautifulSoup import BeautifulSoup
import simplejson


# The google translate API can be found here:
# http://code.google.com/apis/ajaxlanguage/documentation/#Examples
def translate(text, sourceLang = 'en', targetLang = 'pt'):
    try:
        url = "https://www.googleapis.com/language/translate/v2?" + \
              "key=AIzaSyARZORpTevzPWt1XhsIkJUQ0PVZlK4cYTk&q=%s&source=%s&target=%s" % (text, sourceLang, targetLang)
        search_results = urlopen(url)
        json = simplejson.loads(search_results.read())
        return json['data']['translations'][0]['translatedText']
    except:
        return ''

def webPageRead(urlLink):
    # Get a HTML web page to read
    page = urlopen(urlLink)
    # Read from the object, storing the page's contents in 'text'.
    text = page.read()
    page.close()
    return text


def fixHTML(urlLink):
    doc = webPageRead(urlLink)
    textList = []
    soup = BeautifulSoup(doc)
    for s in soup.prettify().split('\n'):
        strippedS = s.strip()
        if strippedS.find(">") == -1 and strippedS.find("<") == -1 and strippedS.find("|") == -1:
            textList.append(strippedS)
    return textList


#repeatedWords = {}
#textFile = open('/tmp/Shakeaspeare_Hamlet_fr.txt', 'w')
#for line in fixHTML():
#    for word in line.split(' '):
#        if not repeatedWords.has_key(word):
#            repeatedWords[word] = translate(word)
#        print repeatedWords[word],
#        textFile.write(repeatedWords[word])
#        textFile.write(' ')
#    print
#    textFile.write('\n')
#textFile.close()
